#include"io430.h"
#include"intrinsics.h"
#include"include.h"
#include"pwm.h"
#include"data_flash.h"
#include"data_param.h"
#include"adc.h"
#include"system_init.h" 
#include"processing_command.h"

extern char paTable[];
extern char paTableLen;

volatile packet  tx_Buffer;
volatile packet  rx_Buffer;

unsigned char from_adress=0;  

short level_battery;

unsigned volatile char flag_run;  
unsigned volatile char flag_stop; 
unsigned volatile  char flag_on_pwm=0; 
unsigned volatile  char flag_run_pwm=0; 
unsigned volatile  char flag_recieve=0;
unsigned short count_packet=0;
unsigned short tmp_count_packet=0;



void Init_wdt(void)
{
    WDTCTL = WDTPW+WDTCNTCL+WDTSSEL;
};


int main( void )
{
  WDTCTL = WDTPW + WDTHOLD;
  for(short i=0;i<10;i++) __delay_cycles(30000);
    
  Init_System_Clock();  
  Init_wdt(); 
  Init_flash();
  Init_Port();  
  
  Out_Disable();
  Out_impulse_Disable();

  Off_PWM(); 
  
  Init_Interrapt_CC2500();
  TI_CC_SPISetup();   
  TI_CC_PowerupResetCCxxxx();               
  writeRFSettings();                        
  TI_CC_SPIWriteBurstReg(TI_CCxxx0_PATABLE, paTable, paTableLen);   
  TI_CC_SPIStrobe(TI_CCxxx0_SRX);  

  Init_TimerA();
  
  while(1)
  {
    __bis_SR_register(CPUOFF + GIE);
    if (flag_recieve==1)
    {
      __disable_interrupt();
      recieve_command();
      __enable_interrupt();
      flag_recieve=0;
    };
    if ((flag_on_pwm==1) && (flag_run_pwm==0))
     {
      P1OUT|=BIT2;
      flag_pwm=0;
      On_PWM(rx_Buffer.data[0],rx_Buffer.data[2]*8,rx_Buffer.data[1]); // addre, current, numer impulse
      flag_on_pwm=0;
      flag_run_pwm=1;
     };
  
  }; 
}



#pragma vector=PORT2_VECTOR
__interrupt void Port2_ISR(void)
{
WDTCTL=WDT_ARST_1000; 


  if(TI_CC_GDO2_PxIFG & TI_CC_GDO2_PIN)
  {
    TI_CC_GDO2_PxIFG &= ~TI_CC_GDO2_PIN;
    flag_recieve=1;
    __bic_SR_register_on_exit(CPUOFF);
  };
}

#pragma vector=WDT_VECTOR
__interrupt void wdt_ISR(void)
{
};